package com.demo.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户注册
 */
public class RegistServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 数据接受
            // 1. 创建一个磁盘文件项工厂对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            // 2. 创建一个核心解析类
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            // 3. 解析 request 请求，返回的是 List 集合，存放的 fileItem 对象
            List<FileItem> list = servletFileUpload.parseRequest(req);
            List<String> hobbyList = new ArrayList<String>();
            for (FileItem fileItem:list) {
                // 判断是普通表单项还是文件上传项
                if (fileItem.isFormField()) {
                    // 普通表单项
                    String name = fileItem.getFieldName(); // 获取表单项的 name 属性
                    String value = fileItem.getString("UTF-8"); // 获取表单项的 value 值
                    System.out.println(name + "    " + value);
                    // 接受复选框数据
                    if ("hobby".equals(name)) {
                        hobbyList.add(fileItem.getString("UTF-8"));
                        System.out.println(name + "    " + hobbyList);
                    }
                } else {
                    // 文件上传项
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        // 4. 遍历集合，获得每个 FileItem ,判断是单项表单还是文件上传
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
